<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import userService from '../services/userService'
import gameService from '../services/gameService'
import type { User, GameRecord } from '../types'

const router = useRouter()
const user = ref<User | null>(null)
const gameRecords = ref<GameRecord[]>([])
const loading = ref(true)
const error = ref('')
const isEditing = ref(false)
const editForm = ref({
  username: '',
  email: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 模拟获取用户信息
    user.value = {
      id: '1',
      username: '海龟汤爱好者',
      email: 'user@example.com',
      avatar: 'https://via.placeholder.com/100',
      joinDate: '2024-01-15',
      gamesPlayed: 42,
      gamesWon: 28,
      winRate: 66.7
    }
    
    // 填充编辑表单
    editForm.value = {
      username: user.value.username,
      email: user.value.email
    }
    
    // 获取游戏记录
    await fetchGameRecords()
  } catch (err: any) {
    error.value = err.message || '获取用户信息失败'
  } finally {
    loading.value = false
  }
}

// 获取游戏记录
const fetchGameRecords = async () => {
  try {
    // 模拟获取游戏记录
    gameRecords.value = [
      {
        id: '1',
        soupId: 'soup1',
        soupTitle: '神秘的敲门声',
        date: '2024-02-15',
        result: 'won',
        turns: 12,
        timeSpent: '15:30',
        hintsUsed: 0
      },
      {
        id: '2',
        soupId: 'soup2',
        soupTitle: '消失的钥匙',
        date: '2024-02-14',
        result: 'lost',
        turns: 20,
        timeSpent: '20:15',
        hintsUsed: 2
      },
      {
        id: '3',
        soupId: 'soup3',
        soupTitle: '午夜电话',
        date: '2024-02-10',
        result: 'won',
        turns: 8,
        timeSpent: '10:25',
        hintsUsed: 1
      }
    ]
  } catch (err: any) {
    console.error('获取游戏记录失败:', err)
  }
}

// 开始编辑用户信息
const startEditing = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
  // 重置表单
  editForm.value = {
    username: user.value?.username || '',
    email: user.value?.email || ''
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!editForm.value.username.trim() || !editForm.value.email.trim()) {
    error.value = '请填写完整的用户信息'
    return
  }
  
  try {
    // 模拟保存用户信息
    if (user.value) {
      user.value.username = editForm.value.username
      user.value.email = editForm.value.email
    }
    isEditing.value = false
    error.value = ''
  } catch (err: any) {
    error.value = err.message || '保存用户信息失败'
  }
}

// 退出登录
const logout = async () => {
  try {
    await userService.logout()
    router.push('/login')
  } catch (err: any) {
    console.error('退出登录失败:', err)
  }
}

// 重新游玩
const playAgain = (soupId: string) => {
  router.push(`/game/${soupId}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="profile-page">
    <div class="profile-container">
      <h1 class="page-title">个人资料</h1>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <p>加载中...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <p>{{ error }}</p>
        <button class="btn-primary" @click="fetchUserInfo">重试</button>
      </div>
      
      <!-- 用户信息 -->
      <div v-else class="user-info-section">
        <div class="user-header">
          <div class="user-avatar">
            <img :src="user?.avatar" :alt="user?.username" />
          </div>
          
          <div v-if="!isEditing" class="user-details">
            <h2 class="user-name">{{ user?.username }}</h2>
            <p class="user-email">{{ user?.email }}</p>
            <p class="user-join-date">注册日期: {{ user?.joinDate }}</p>
          </div>
          
          <div v-else class="user-edit-form">
            <div class="form-group">
              <label for="username">用户名</label>
              <input 
                id="username"
                v-model="editForm.username"
                type="text"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label for="email">邮箱</label>
              <input 
                id="email"
                v-model="editForm.email"
                type="email"
                class="form-input"
              />
            </div>
          </div>
          
          <div class="user-actions">
            <button 
              v-if="!isEditing" 
              class="btn-secondary" 
              @click="startEditing"
            >
              编辑资料
            </button>
            <div v-else class="edit-actions">
              <button class="btn-primary" @click="saveUserInfo">
                保存
              </button>
              <button class="btn-secondary" @click="cancelEditing">
                取消
              </button>
            </div>
            <button class="btn-danger" @click="logout">
              退出登录
            </button>
          </div>
        </div>
        
        <!-- 用户统计 -->
        <div class="user-stats">
          <div class="stat-item">
            <div class="stat-value">{{ user?.gamesPlayed }}</div>
            <div class="stat-label">总游玩次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ user?.gamesWon }}</div>
            <div class="stat-label">获胜次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ user?.winRate }}%</div>
            <div class="stat-label">胜率</div>
          </div>
        </div>
      </div>
      
      <!-- 游戏记录 -->
      <div v-if="!loading && !error" class="game-records-section">
        <h2 class="section-title">游戏记录</h2>
        
        <div v-if="gameRecords.length === 0" class="empty-records">
          <p>暂无游戏记录</p>
          <button class="btn-primary" @click="router.push('/')">
            去首页游玩
          </button>
        </div>
        
        <div v-else class="records-list">
          <div 
            v-for="record in gameRecords" 
            :key="record.id" 
            class="record-item"
          >
            <div class="record-info">
              <h3 class="record-title">{{ record.soupTitle }}</h3>
              <div class="record-meta">
                <span class="record-date">{{ record.date }}</span>
                <span class="record-result" :class="record.result">
                  {{ record.result === 'won' ? '胜利' : '失败' }}
                </span>
              </div>
            </div>
            
            <div class="record-stats">
              <div class="record-stat">
                <span class="stat-label">回合数</span>
                <span class="stat-value">{{ record.turns }}/20</span>
              </div>
              <div class="record-stat">
                <span class="stat-label">用时</span>
                <span class="stat-value">{{ record.timeSpent }}</span>
              </div>
              <div class="record-stat">
                <span class="stat-label">提示</span>
                <span class="stat-value">{{ record.hintsUsed }}</span>
              </div>
            </div>
            
            <div class="record-actions">
              <button class="btn-secondary" @click="playAgain(record.soupId)">
                重新游玩
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.profile-page {
  min-height: calc(100vh - 120px);
  background-color: #f5f7fa;
  padding: 40px 0;
}

.profile-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 32px;
  color: #262626;
  margin-bottom: 32px;
  text-align: center;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  background: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  color: #666;
}

/* 用户信息部分 */
.user-info-section {
  background: white;
  border-radius: 8px;
  padding: 32px;
  margin-bottom: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #f0f0f0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 24px;
  color: #262626;
  margin: 0 0 8px 0;
}

.user-email {
  font-size: 16px;
  color: #666;
  margin: 0 0 4px 0;
}

.user-join-date {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.user-edit-form {
  flex: 1;
  display: flex;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}

.form-group label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.form-input {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

/* 用户统计 */
.user-stats {
  display: flex;
  gap: 40px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #1890ff;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 游戏记录部分 */
.game-records-section {
  background: white;
  border-radius: 8px;
  padding: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 24px;
  color: #262626;
  margin: 0 0 24px 0;
}

.empty-records {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-records p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-item {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.record-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.record-info {
  flex: 1;
}

.record-title {
  font-size: 18px;
  color: #262626;
  margin: 0 0 8px 0;
}

.record-meta {
  display: flex;
  gap: 16px;
  align-items: center;
}

.record-date {
  font-size: 14px;
  color: #666;
}

.record-result {
  font-size: 14px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
}

.record-result.won {
  background-color: #f6ffed;
  color: #52c41a;
}

.record-result.lost {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.record-stats {
  display: flex;
  gap: 24px;
}

.record-stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.record-stat .stat-label {
  font-size: 12px;
  color: #999;
}

.record-stat .stat-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.record-actions {
  display: flex;
  gap: 8px;
}

/* 按钮样式 */
.btn-primary,
.btn-secondary,
.btn-danger {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
}

.btn-primary:hover {
  background-color: #40a9ff;
}

.btn-secondary {
  background-color: white;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.btn-secondary:hover {
  background-color: #e6f7ff;
}

.btn-danger {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.btn-danger:hover {
  background-color: #ff4d4f;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-header {
    flex-wrap: wrap;
  }
  
  .user-avatar {
    margin: 0 auto;
  }
  
  .user-details,
  .user-edit-form {
    width: 100%;
  }
  
  .user-edit-form {
    flex-direction: column;
  }
  
  .user-actions {
    width: 100%;
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .user-stats {
    justify-content: space-around;
    gap: 20px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .record-item {
    flex-wrap: wrap;
  }
  
  .record-info,
  .record-stats,
  .record-actions {
    width: 100%;
  }
  
  .record-stats {
    justify-content: space-around;
    gap: 16px;
    padding: 16px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .record-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .profile-page {
    padding: 20px 0;
  }
  
  .profile-container {
    padding: 0 16px;
  }
  
  .page-title {
    font-size: 24px;
    margin-bottom: 24px;
  }
  
  .user-info-section,
  .game-records-section {
    padding: 20px;
  }
  
  .user-header {
    gap: 16px;
    margin-bottom: 24px;
  }
  
  .user-avatar {
    width: 100px;
    height: 100px;
  }
  
  .user-name {
    font-size: 20px;
  }
  
  .user-actions {
    flex-direction: column;
  }
  
  .edit-actions {
    width: 100%;
  }
  
  .user-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .stat-item {
    flex-direction: row;
    justify-content: space-between;
  }
  
  .section-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .record-title {
    font-size: 16px;
  }
  
  .record-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .record-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .record-stat {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }
}
</style>